﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using EPiAbstractions.Community.ImageGallery;
using EPiServer.Common;
using EPiServer.Common.Publishing;
using EPiServer.Common.Queries;
using EPiServer.Community.ImageGallery;
using EPiServer.Community.ImageGallery.Queries;
using JoelAbrahamsson.WebUtilities;

namespace JoelAbrahamsson.BlogExtensions
{
    public class AvatarProvider
    {
        public const string GravatarImageGalleryName = "Gravatars";
        public const string DefaultAvatarsImageGalleryName = "DefaultAvatars";

        private string _defaultAvatarImagesPath;

        public AvatarProvider(IImageGalleryHandlerFacade imageGalleryHandlerFacade, string defaultAvatarImagesPath)
        {
            ImageGalleryHandlerFacade = imageGalleryHandlerFacade;
            _defaultAvatarImagesPath = defaultAvatarImagesPath;
        }

        public virtual string GetAvatarUrl(IAuthor author)
        {
            ImageQuery query = GetAvatarQuery(author);
            ImageCollection images = ImageGalleryHandlerFacade.GetQueryResult(query);
            if (images.Count > 0)
                return images[0].GetThumbnail(80, 80, ThumbnailFormat.ReduceAndCrop).Url;


            string gravatarUrl = GetGravatarUrl(author);
            WebRequest webRequest = WebRequest.Create(gravatarUrl);
            WebResponse response = null;
            try
            {
                response = webRequest.GetResponse();
                Image avatarImage = new Image(author.Email, author.Email, response.GetResponseStream(), GravatarImageGallery, PublishState.Published, null);
                avatarImage = ImageGalleryHandler.AddImage(avatarImage);
                QueryHandler.RemoveQueryResultCache(query);
                return avatarImage.GetThumbnail(80, 80, ThumbnailFormat.ReduceAndCrop).Url;
            }
            catch (WebException)
            {
            }

            string randomFilename = string.Format("{0}.gif", new Random().Next(1, 12));
            FileStream imageStream = new FileStream(_defaultAvatarImagesPath + randomFilename, FileMode.Open, FileAccess.Read);
            Image randomImage = new Image(author.Email, author.Email, imageStream, GravatarImageGallery, PublishState.Published, null);
            randomImage = ImageGalleryHandlerFacade.AddImage(randomImage);
            QueryHandler.RemoveQueryResultCache(query);
            return randomImage.GetThumbnail(80, 80, ThumbnailFormat.ReduceAndCrop).Url;
        }

        private ImageQuery GetAvatarQuery(IAuthor author)
        {
            ImageQuery query = new ImageQuery();
            query.Name = new StringCriterion();
            query.Name.Value = author.Email;
            query.ImageGallery = new ImageGalleryCriterion();
            query.ImageGallery.ID = new IntegerCriterion();
            query.ImageGallery.ID.Value = GravatarImageGallery.ID;
            return query;
        }

        private string GetGravatarUrl(IAuthor author)
        {
            return "http://www.gravatar.com/avatar/" + author.Email.ToLower().Trim().GetMD5Hash() + "?d=404";
        }

        private IImageGalleryHandlerFacade ImageGalleryHandlerFacade { get; set; }

        public virtual ImageGallery GravatarImageGallery
        {
            get
            {
                ImageGalleryQuery query = new ImageGalleryQuery();
                query.Name = new StringCriterion();
                query.Name.Value = GravatarImageGalleryName;
                ImageGalleryCollection returnedGalleries = ImageGalleryHandlerFacade.GetQueryResult(query);
                if (returnedGalleries.Count > 0)
                    return returnedGalleries[0];

                ImageGallery gallery = new ImageGallery(GravatarImageGalleryName, GravatarImageGalleryName);
                return ImageGalleryHandlerFacade.AddImageGallery(gallery);
            }
        }
    }
}
